<?php

declare (strict_types=1);

namespace app\webapi\common;

use app\webapi\vms\model\ChannelModel;
use app\webapi\vms\model\SystemChannelModel;
use app\webapi\vms\model\WebsiteModel;
use Godruoyi\Snowflake\Snowflake;
use library\OWException;
use think\facade\Db;

/**
 * @基础控制器
 */
class BaseService{
    /**
     * @desc 生成雪花算法id
     * @return string
     * @author zhaozhiwei
     * @time 2023/12/19-9:50
     */
    public function createSnowId(){
        $snowflake = new Snowflake(100, 100);
        return $snowflake->id();
    }

    /**
     * @desc 生成草稿网站
     * @param $owner
     * @return int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/19-9:51
     */
    public function generateDraftWebsite($owner)
    {
        //获取栏目模板信息
        $system_channel_list = SystemChannelModel::select()->toArray();
        if (empty($system_channel_list)) {
            throw new OWException('系统栏目模板不存在');
        }

        try {
            //启动事务
            Db::startTrans();
            //补全网站必要默认信息
            $params['domain_prefix'] = 'http://';
            $params['language'] = 'cn';
            $params['owner'] = $owner;
            $params['name'] = $owner.uniqid(uniqid(). rand(10000,99999));
            //写入网站数据
            $website_id = (new WebsiteModel())->insertGetId($params);
            //写入第一条数据
            $time = time();
            $init_insert = [
                'name' => $system_channel_list[0]['name'],
                'website_id' => $website_id,
                'system_channel_id' => $system_channel_list[0]['id'],
                'root_pid' => $system_channel_list[0]['root_pid'],
                'pid' => 0,
                'create_time' => $time,
                'update_time' => $time
            ];
            $init_id = ChannelModel::insertGetId($init_insert);

            //计算子级栏目pid后,批量写入栏目信息
            $save_data = [];
            foreach ($system_channel_list as $key => $v) {
                if ($key > 0) {
                    $tmp_pid = $v['pid'] == 0 ? 0 : $init_id + $v['pid_diff_of_index'];
                    $tmp_insert = [
                        'name' => $v['name'],
                        'website_id' => $website_id,
                        'system_channel_id' => $v['id'],
                        'root_pid' => $v['root_pid'],
                        'pid' => $tmp_pid,
                    ];
                    array_push($save_data, $tmp_insert);
                }
            }
            (new ChannelModel())->saveAll($save_data);

            //提交事务
            Db::commit();

            //定义预期对照数组
            $compare_arr = [];
            for ($i = 0; $i < count($system_channel_list); $i++) {
                array_push($compare_arr, $init_id + $i);
            }
            //新写入的数据查询校验
            $id_arr = ChannelModel::where(['website_id' => $website_id])->column('id');
            if (!empty(array_diff($id_arr, $compare_arr))) {
                Db::rollback();
                throw new OWException('写入数据有误');
            }
        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            throw new OWException('初始化栏目信息失败', $e->getMessage());
        }

        return $website_id;
    }
}